# == Schema Information
# Schema version: 6
#
# Table name: votes
#
#  id            :integer(11)   not null, primary key
#  vote          :boolean(1)    
#  created_at    :datetime      not null
#  voteable_type :string(15)    default(""), not null
#  voteable_id   :integer(11)   default(0), not null
#  user_id       :integer(11)   default(0), not null
#

class Vote < ActiveRecord::Base
  belongs_to :user
  validates_inclusion_of :vote, :in => [0,1]
  validates_presence_of :voteable_type, :voteable_id, :user_id, :allow_nil => false
  validates_numericality_of :voteable_id, :user_id, :vote, :allow_nil => false
  validates_exclusion_of :voteable_id, :user_id, :in => [0], :message => "no superusers allowed"
  validates_uniqueness_of :user_id, :scope => [ :user_id, :voteable_type, :voteable_id ]
  
  def validate
    unless self.user(true)
      self.errors.add(:user_id, "is not a valid user id")
    end

    if self.voteable_id == 0 or self.voteable_id.nil?
      self.errors.add(:voteable_id, "must be positive")
    end
    
    unless self.voteable_type.blank? or self.voteable_type.nil?
      begin
       self.voteable_type.constantize
       if self.voteable_type.constantize.find(self.voteable_id)
         unless self.voteable_type.constantize.ancestors.include?(ActiveRecord::Base)
          self.errors.add(:voteable_type, "is not a subclass of activerecord")
         end
       end
      rescue NameError
        self.errors.add(:voteable_type, "does not contain a valid class name")
      rescue ActiveRecord::RecordNotFound
        self.errors.add(:voteable_id, "is not a valid #{self.voteable_type} object")
      end
    end
  end
end
